<template>
  <div>
    <!-- 顶部面包屑标识与导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 后台管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/admin/content/article' }">内容管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: './' }">文章管理</el-breadcrumb-item>
      <el-breadcrumb-item>发布文章</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 添加数据的表单 -->
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="文章类别" prop="categoryId">
        <el-cascader
            clearable
            style="width: 100%;"
            placeholder="请选择文章类别"
            v-model="ruleForm.categoryId"
            :options="categoryOptions"></el-cascader>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="摘要" prop="brief">
        <el-input type="textarea" v-model="ruleForm.brief"
                  :autosize="{ minRows: 3, maxRows: 5}"
                  maxlength="255" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="封面图" prop="coverUrl">
        <div class="picture-preview" v-if="ruleForm.coverUrl">
          <el-image class="image"
                    :src="ruleForm.coverUrl"
                    fit="cover"></el-image>
        </div>
        <el-upload
            class="picture-uploader"
            action="http://localhost:9080/resources/upload/image/article"
            :show-file-list="false"
            :on-success="handleUploadSuccess">
          <i class="el-icon-upload picture-uploader-icon"></i>
          <div class="picture-uploader-text">仅允许上传 <i>JPG</i> / <i>PNG</i> 格式的图片</div>
          <div class="picture-uploader-text">仅允许上传不超过 <i>5MB</i> 的图片</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章详情">
        <div id="wangEditor"></div>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input v-model="ruleForm.tags"></el-input>
      </el-form-item>
      <el-form-item label="排序序号" prop="sort">
        <el-input v-model="ruleForm.sort"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">发布</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button type="warning" @click="gotoList">返回列表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 父级类别的下拉菜单的选项数据
      categoryOptions: [],
      // 表单
      ruleForm: {
        categoryId: [],
        title: '',
        brief: '',
        coverUrl: '',
        tags: '[{\"id\":26, \"name\":\"经验\"}]',
        sort: '99'
      },
      // 表单规则
      rules: {
        categoryId: [
          {required: true, message: '请选择文章类别', trigger: 'change'}
        ],
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 2, max: 150, message: '长度在 2 到 150 个字符', trigger: 'blur'}
        ],
        brief: [
          {required: true, message: '请输入摘要', trigger: 'blur'},
          {min: 2, max: 255, message: '长度在 2 到 255 个字符', trigger: 'blur'}
        ],
        coverUrl: [
          {required: true, message: '请上传封面图', trigger: 'blur'}
        ],
        tags: [
          {required: true, message: '请选择标签', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'},
          {pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是0~99之间的值', trigger: 'blur'}
        ]
      },
      // 富文本编辑器
      editor: {}
    };
  },
  methods: {
    // 返回列表
    gotoList() {
      this.$router.push('/admin/content/article');
    },
    // 初始化富文本编辑器
    initWangEditor() {
      this.editor = new this.wangEditor('#wangEditor');
      this.editor.config.uploadImgServer = 'http://localhost:9080/resources/upload/image/article';
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadImgHooks = {
        customInsert: function(insertImgFn, result) {
          insertImgFn(result.data.url);
        }
      }
      this.editor.config.zIndex = 1;
      this.editor.create();
    },
    // 上传成功后的回调
    handleUploadSuccess(response) {
      console.log(response)
      if (response.state == 20000) {
        this.ruleForm.coverUrl = response.data.url;
      } else {
        let title = '操作失败';
        this.$alert(response.message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      }
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:9080/content/articles/add-new';
          console.log('url = ' + url);

          if (Array.isArray(this.ruleForm.categoryId)) {
            this.ruleForm.categoryId = this.ruleForm.categoryId[this.ruleForm.categoryId.length - 1];
          }

          this.ruleForm.detail = this.editor.txt.html();
          let formData = this.qs.stringify(this.ruleForm);
          console.log('formData = ' + formData);

          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
              .post(url, formData).then((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              let message = '发布文章成功！';
              this.$alert(message, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.resetForm(formName);
                }
              });
            } else {
              let title = '操作失败';
              this.$alert(jsonResult.message, title, {
                confirmButtonText: '确定',
                callback: action => {
                }
              });
            }
          }).catch(error => {
            let title = '错误';
            let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
            this.$alert(message, title, {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
            console.log(error);
          });
        } else {
          console.log('请求参数格式错误！');
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editor.txt.clear();
    },
    // 加载类别树的数据
    loadCategoryTree() {
      let url = 'http://localhost:9080/content/categories/tree';
      console.log('url = ' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('localJwt')}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.categoryOptions = jsonResult.data;
        } else {
          let title = '操作失败';
          this.$alert(jsonResult.message, title, {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程中出现错误，请打开浏览器的控制台查看详细错误信息！';
        this.$alert(message, title, {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
        console.log(error);
      });
    }
  },
  mounted() {
    this.loadCategoryTree();
    this.initWangEditor();
  }
}
</script>

<style>
.picture-uploader {
  float: left;
  width: 240px;
  height: 135px;
  margin-right: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.picture-uploader .picture-uploader-icon {
  width: 240px;
  height: 80px;
  font-size: 58px;
  color: #8c939d;
  line-height: 80px;
  text-align: center;
}

.picture-uploader .picture-uploader-text {
  width: 240px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  font-size: 10px;
  color: #8c939d;
}

.picture-uploader .picture-uploader-text i {
  font-size: 10px;
  font-weight: bold;
  font-style: normal;
  color: #F56C6C;
}

.picture-preview {
  width: 240px;
  height: 135px;
  margin-right: 20px;
  border: 1px solid #e8e6e6;
  border-radius: 6px;
  float: left;
  display: inline;
  position: relative;
}

.picture-preview .image {
  width: 240px;
  height: 135px;
  border-radius: 6px;
}
</style>